import { useState } from 'react';
import { useMcpStore } from '../stores/useMcpStore';
import { Button } from '../components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../components/ui/card';
import { Badge } from '../components/ui/badge';
import { Plus, Wrench, Settings, Trash2, Power, PowerOff } from 'lucide-react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '../components/ui/dialog';
import { Input } from '../components/ui/input';
import { Label } from '../components/ui/label';
import { Textarea } from '../components/ui/textarea';
import { Switch } from '../components/ui/switch';
import { toast } from '../hooks/use-toast';
import apiService from '../lib/api';

export default function ToolsPage() {
  const { mcpServices, mcpTools, addMcpService, removeMcpService } = useMcpStore();
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [newService, setNewService] = useState({
    name: '',
    command: '',
    args: [] as string[],
    env: {} as Record<string, string>,
    enabled: true,
  });

  const handleCreateService = async () => {
    try {
      const service = await apiService.createMcpService(newService);
      addMcpService(service);
      setIsCreateDialogOpen(false);
      setNewService({
        name: '',
        command: '',
        args: [],
        env: {},
        enabled: true,
      });
      toast({
        title: "MCP Service Created",
        description: `Service "${service.name}" has been created successfully.`,
      });
    } catch (error) {
      toast({
        title: "Error",
        description: "Failed to create MCP service. Please try again.",
        variant: "destructive",
      });
    }
  };

  const handleDeleteService = async (serviceId: string) => {
    try {
      await apiService.deleteMcpService(serviceId);
      removeMcpService(serviceId);
      toast({
        title: "Service Deleted",
        description: "MCP service has been deleted successfully.",
      });
    } catch (error) {
      toast({
        title: "Error",
        description: "Failed to delete service. Please try again.",
        variant: "destructive",
      });
    }
  };

  const handleToggleService = async (serviceId: string, enabled: boolean) => {
    try {
      // TODO: Implement service toggle
      console.log('Toggle service:', serviceId, enabled);
      toast({
        title: enabled ? "Service Enabled" : "Service Disabled",
        description: `Service has been ${enabled ? 'enabled' : 'disabled'}.`,
      });
    } catch (error) {
      toast({
        title: "Error",
        description: "Failed to toggle service. Please try again.",
        variant: "destructive",
      });
    }
  };

  return (
    <div className="flex flex-col h-full p-6">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold">Tools & Extensions</h1>
          <p className="text-slate-600 dark:text-slate-400">
            Manage MCP services and available tools
          </p>
        </div>
        
        <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="h-4 w-4 mr-2" />
              Add MCP Service
            </Button>
          </DialogTrigger>
          <DialogContent className="sm:max-w-[425px]">
            <DialogHeader>
              <DialogTitle>Add MCP Service</DialogTitle>
              <DialogDescription>
                Configure a new Model Context Protocol service.
              </DialogDescription>
            </DialogHeader>
            <div className="grid gap-4 py-4">
              <div className="grid gap-2">
                <Label htmlFor="name">Service Name</Label>
                <Input
                  id="name"
                  value={newService.name}
                  onChange={(e) => setNewService({ ...newService, name: e.target.value })}
                  placeholder="Enter service name"
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="command">Command</Label>
                <Input
                  id="command"
                  value={newService.command}
                  onChange={(e) => setNewService({ ...newService, command: e.target.value })}
                  placeholder="uvx package-name"
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="args">Arguments (one per line)</Label>
                <Textarea
                  id="args"
                  value={newService.args.join('\n')}
                  onChange={(e) => setNewService({ 
                    ...newService, 
                    args: e.target.value.split('\n').filter(arg => arg.trim()) 
                  })}
                  placeholder="--arg1&#10;--arg2"
                />
              </div>
              <div className="flex items-center space-x-2">
                <Switch
                  id="enabled"
                  checked={newService.enabled}
                  onCheckedChange={(checked) => setNewService({ ...newService, enabled: checked })}
                />
                <Label htmlFor="enabled">Enable service</Label>
              </div>
            </div>
            <div className="flex justify-end gap-2">
              <Button variant="outline" onClick={() => setIsCreateDialogOpen(false)}>
                Cancel
              </Button>
              <Button onClick={handleCreateService} disabled={!newService.name || !newService.command}>
                Add Service
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <div className="flex-1 overflow-auto space-y-6">
        {/* MCP Services */}
        <div>
          <h2 className="text-lg font-semibold mb-4">MCP Services</h2>
          {mcpServices.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-32 text-center border-2 border-dashed border-slate-300 dark:border-slate-700 rounded-lg">
              <Wrench className="h-8 w-8 text-slate-400 mb-2" />
              <p className="text-slate-600 dark:text-slate-400">No MCP services configured</p>
              <Button 
                variant="link" 
                onClick={() => setIsCreateDialogOpen(true)}
                className="mt-2"
              >
                Add your first service
              </Button>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {mcpServices.map((service) => (
                <Card key={service.id} className="hover:shadow-md transition-shadow">
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <CardTitle className="text-lg flex items-center gap-2">
                        {service.enabled ? (
                          <Power className="h-4 w-4 text-green-500" />
                        ) : (
                          <PowerOff className="h-4 w-4 text-slate-400" />
                        )}
                        {service.name}
                      </CardTitle>
                      <div className="flex items-center gap-1">
                        <Switch
                          checked={service.enabled}
                          onCheckedChange={(checked) => handleToggleService(service.id, checked)}
                        />
                        <Button variant="ghost" size="sm">
                          <Settings className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleDeleteService(service.id)}
                          className="text-red-600 hover:text-red-700"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                    <CardDescription>
                      <code className="text-xs bg-slate-100 dark:bg-slate-800 px-1 py-0.5 rounded">
                        {service.command} {service.args?.join(' ')}
                      </code>
                    </CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-2">
                      <Badge variant={service.enabled ? "default" : "secondary"}>
                        {service.enabled ? "Active" : "Inactive"}
                      </Badge>
                      {service.status && (
                        <Badge variant="outline">{service.status}</Badge>
                      )}
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </div>

        {/* Available Tools */}
        <div>
          <h2 className="text-lg font-semibold mb-4">Available Tools</h2>
          {mcpTools.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-32 text-center border-2 border-dashed border-slate-300 dark:border-slate-700 rounded-lg">
              <Wrench className="h-8 w-8 text-slate-400 mb-2" />
              <p className="text-slate-600 dark:text-slate-400">No tools available</p>
              <p className="text-sm text-slate-500 dark:text-slate-500">
                Tools will appear here when MCP services are connected
              </p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {mcpTools.map((tool) => (
                <Card key={tool.name} className="hover:shadow-md transition-shadow">
                  <CardHeader>
                    <CardTitle className="text-lg">{tool.name}</CardTitle>
                    <CardDescription>{tool.description}</CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-2">
                      <Badge variant="outline">{tool.type || 'function'}</Badge>
                      {tool.parameters && (
                        <div className="text-xs text-slate-600 dark:text-slate-400">
                          {Object.keys(tool.parameters.properties || {}).length} parameters
                        </div>
                      )}
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}